#coding:utf-8
import serial
import sys
#import psutil as PS
import os
import re
#import subprocess as SPO

"""
   树莓PI/笔记本/PC机通过本机串口向单片机串口发送升级的ROV固件的脚本。
   先运行脚本，再复位已烧写bootloader的单片机。脚本中设置了等待MCU串口输出数据的超时时间为120秒。
"""

def foo(uart_dev,bin_file):
    try:
        uart=serial.Serial(uart_dev,baudrate=115200,timeout=120)
    except serial.SerialException as e:
        print(e)
        exit()
    #if not uart.is_open():
    #    uart.open()
    print("串口设备<"+uart_dev+">已打开。向对端发送复位命令")
    cmd=bytes('ggo 2\n','utf8')
    uart.write(cmd)
    print('等待对端bootloader发送标识消息~~')
    bytes0=uart.read_until()
    bytes0=uart.read_until()
    bytes1=uart.readline()
    bytes2=uart.readline()
    bss3  =uart.readline()
    str1=bytes1.decode('gb2312')
    str2=bytes2.decode('gb2312')
    str3=  bss3.decode('gb2312')
    if str1.find("等待升级")!= -1 or str2.find("等待升级")!= -1 or str3.find("等待升级")!= -1:
        f=open(bin_file,'rb')
        data=f.read()
        print("[脚本输出] 即将向串口发送APP固件")
        uart.write(data)
    while True:
        bytes9 = uart.readline()
        str = bytes9.decode('gb2312')
        if str.find('开始执行已有代码')!= -1:
            print("[脚本输出] MCU固件升级成功！")
            print("MCU串口回显： "+str,end="")
            break
        else:
            print("MCU串口回显: "+str,end="")

'''
def kill_nodejs_program():
    pids = PS.pids()
    for id in pids:
        p = PS.Process(id)
        pname = p.name()
        print("pid=%s , Name: %s"%(id,pname))
 '''
def kill_nodejs_program():
    pss=["node.*rov_main_entry\.js$","node.*njs_serport\.js$","ffmpeg.*/pull/test$"]
    for ss in pss:
        ret=os.popen("ps -ef|grep %s"%ss)
        ss=ret.read()
        if(len(ss)>1):
            print("查找到进程: %s"%ss)
            gg=re.search('(\d+)\s',ss,0)
            pos=gg.span()
            pid=ss[pos[0] : pos[1]]
            print("即将杀死进程ID: %s"%pid)
            os.system("sudo kill %s"%pid)
    print("所有相关进程被清除,接下来进行app升级。。。")
    
def restart_all():
    os.system("node /home/pabi/rov/rov_main_entry.js >> /home/pabi/rov/rov_log.log &")
    #pass
    
if __name__ == '__main__':
    if len(sys.argv)!=3:
        print("脚本用法： python3  "+sys.argv[0]+"  <串口设备名>  <待升级的BIN文件路径及名称>")
        exit()
    kill_nodejs_program()
    foo(sys.argv[1],sys.argv[2])
    restart_all()
    
